package com.cxyzy.demo

import android.text.TextUtils
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

import java.util.*

object JsonUtil {
    /**
     * 将json字符串转化为map
     *
     * @param jsonStr json字符串
     */
    @Throws(JSONException::class)
    fun jsonToMap(jsonStr: String): Map<String, Any>? {
        return if (TextUtils.isEmpty(jsonStr)) {
            null
        } else jsonToMap(JSONObject(jsonStr))
    }

    /**
     * 将json对象转化为map
     *
     * @param json json对象
     */
    @Throws(JSONException::class)
    fun jsonToMap(json: JSONObject): Map<String, Any> {
        var retMap: Map<String, Any> = HashMap()

        if (json !== JSONObject.NULL) {
            retMap = toMap(json)
        }
        return retMap
    }

    @Throws(JSONException::class)
    private fun toMap(`object`: JSONObject): Map<String, Any> {
        val map = HashMap<String, Any>()

        val keysItr = `object`.keys()
        while (keysItr.hasNext()) {
            val key = keysItr.next()
            var value = `object`.get(key)

            if (value is JSONArray) {
                value = toList(value)
            } else if (value is JSONObject) {
                value = toMap(value)
            }
            map[key] = value
        }
        return map
    }

    @Throws(JSONException::class)
    private fun toList(array: JSONArray): List<Any> {
        val list = ArrayList<Any>()
        for (i in 0 until array.length()) {
            var value = array.get(i)
            if (value is JSONArray) {
                value = toList(value)
            } else if (value is JSONObject) {
                value = toMap(value)
            }
            list.add(value)
        }
        return list
    }
}
